package com.jshan.config;

import cn.dev33.satoken.stp.StpInterface;
import com.jshan.base.entity.SysMenu;
import com.jshan.base.entity.SysRole;
import com.jshan.base.entity.SysUserRole;
import com.jshan.mapper.SysMenuMapper;
import com.jshan.mapper.SysRoleMapper;
import com.jshan.mapper.SysUserRoleMapper;
import com.jshan.mapper.SysRoleMenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    private final SysUserRoleMapper userRoleMapper;
    private final SysRoleMapper roleMapper;
    private final SysMenuMapper menuMapper;
    private final SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 获取用户角色列表
        List<SysUserRole> userRoles = userRoleMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, loginId));

        if (userRoles.isEmpty()) {
            return new ArrayList<>();
        }

        List<Long> roleIds = userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        List<SysRole> roles = roleMapper.selectBatchIds(roleIds);

        return roles.stream()
                .map(SysRole::getRoleKey)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 获取用户角色列表
        List<SysUserRole> userRoles = userRoleMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, loginId));

        if (userRoles.isEmpty()) {
            return new ArrayList<>();
        }

        List<Long> roleIds = userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        // 获取角色对应的菜单ID列表
        List<Long> menuIds = roleMenuMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.jshan.base.entity.SysRoleMenu>()
                        .in(com.jshan.base.entity.SysRoleMenu::getRoleId, roleIds))
                .stream()
                .map(com.jshan.base.entity.SysRoleMenu::getMenuId)
                .collect(Collectors.toList());

        if (menuIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取菜单权限列表
        List<SysMenu> menus = menuMapper.selectBatchIds(menuIds);

        return menus.stream()
                .map(SysMenu::getPerms)
                .filter(perms -> perms != null && !perms.isEmpty())
                .collect(Collectors.toList());
    }
}
